//
//  MSImageView.m
//  Musou
//
//  Created by luo danal on 4/24/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "MSImageView.h"
#import "MSUIImage+Additiions.h"

@interface MSImageView ()
@property (retain,nonatomic) NSMutableData *recvData;
@property (retain,nonatomic) UIActivityIndicatorView *indicator;
@property (retain,nonatomic) MSProgressBar *progressbar;
@property (assign,nonatomic) NSInteger totalLen;
@property (assign,nonatomic) NSInteger recvLen;
@property (retain,nonatomic) NSURLConnection *conn;
@end

@implementation MSImageView
@synthesize touchable = _touchable;
@synthesize delegate = _delegate;
@synthesize url = _url;
@synthesize recvData = _recvData;
@synthesize placeholder = _placeholder;
@synthesize indicator = _indicator;
@synthesize progressbar = _progressbar;
@synthesize totalLen = _totalLen;
@synthesize recvLen = _recvLen;
@synthesize style = _style;
@synthesize useThumbnail = _useThumbnail;
@synthesize conn = _conn;
@synthesize animatedShow = _animatedShow;
@synthesize autoLoading = _autoLoading;
@synthesize loading = _loading;

- (void)dealloc{
    [_conn release];
    _conn = nil;
    [_indicator release];
    [_placeholder release];
    _placeholder = nil;
    [_recvData release];
    _recvData = nil;
    [_url release];
    [super dealloc];
}

+ (NSString *)cacheNameForUrl:(NSString *)url{
    if ([url length] < 7) {
        return nil;
    }
    url = [url substringFromIndex:7];    //http://
    NSRange range = [url rangeOfString:@"/"];
    if (range.length < 1) {
        return nil;
    }
    NSString *fileName = [url substringFromIndex:range.location];
    fileName = [fileName stringByReplacingOccurrencesOfString:@"/|\\?|\\*" withString:@"-" options:NSRegularExpressionSearch range:NSMakeRange(0, fileName.length)];
    return fileName;
}

+ (NSString *)thumbnailCacheNameForUrl:(NSString *)url{
    NSString *fileName = [[self class] cacheNameForUrl:url];
    NSString *extension = [fileName pathExtension];
    fileName = [fileName stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@".%@", extension]
                                               withString:[NSString stringWithFormat:@"_thumb.%@",extension]];
    return fileName;
}

+ (UIImage *)cacheImageForUrl:(NSString *)url{
    NSString *file = [MSImageView cacheNameForUrl:url];
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    path = [path stringByAppendingPathComponent:file];
    return [UIImage imageWithContentsOfFile:path];    
}

- (NSString *)cacheName{
   return [[self class] cacheNameForUrl:self.url];
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.animatedShow = YES;
        self.autoLoading = YES;
        _completionBlock = NULL;
        _progressbar = [MSProgressBar standardBar];
        CGRect rect = _progressbar.frame;
        if (frame.size.width < rect.size.width) {
            rect.size.width = frame.size.width - 20;
            _progressbar.frame = rect;
        }
        _progressbar.center = self.center;
        [self addSubview:_progressbar];
        
    }
    return self;
}

- (id)initWithPlaceholder:(UIImage *)image{
    self = [super initWithImage:image];
    if (self) {
        self.placeholder = image;
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame style:(MSImageViewStyle)style{
    self = [super initWithFrame:frame];
    if (self) {
        self.style = style;
        self.animatedShow = YES;
        self.autoLoading = YES;
        _completionBlock = NULL;
        CGPoint center = CGPointMake(frame.size.width/2, frame.size.height/2);
        if (style == kMSImageViewStyleProgressBar) {
            _progressbar = [MSProgressBar standardBar];
            _progressbar.center = center;
            [self addSubview:_progressbar];
        } else {
            _indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
            _indicator.center = center;
            [self addSubview:_indicator];
        }
    }
    return self;
}

- (void)setFrame:(CGRect)frame{
    [super setFrame:frame];
    CGRect rect = _progressbar.frame;
    if (frame.size.width < rect.size.width) {
        rect.size.width = frame.size.width - 20;
        _progressbar.frame = rect;
    }
    CGPoint center = CGPointMake(frame.size.width/2, frame.size.height/2);
    _indicator.center = center;
    _progressbar.center  = center;
}

- (void)setCompletionBlock:(void (^)(MSImageView *))block{
    _completionBlock = block;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

- (void)finishingAnimation{
    [UIView transitionWithView:self 
                      duration:.4f 
                       options:UIViewAnimationOptionTransitionFlipFromLeft|UIViewAnimationOptionAllowUserInteraction 
                    animations:NULL 
                    completion:NULL];
}

- (void)startLoading{
    self.loading = NO;
    
    NSString *fileName = [self cacheName];
    if (self.useThumbnail) {
        fileName = [[self class] thumbnailCacheNameForUrl:self.url];
    }
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    path = [path stringByAppendingPathComponent:fileName];
    NSFileManager *fm = [NSFileManager defaultManager];
    if ([fm fileExistsAtPath:path]) {
        if (self.style == kMSImageViewStyleProgressBar) {
            _progressbar.hidden = YES;
        }
        self.image = [UIImage imageWithContentsOfFile:path];
        if (_completionBlock != NULL) {
            _completionBlock(self);
        }
        if (_delegate && [_delegate respondsToSelector:@selector(imageDidFinishLoading:)]) {
            [_delegate imageDidFinishLoading:self];
        }
    } else {
        if (self.style == kMSImageViewStyleProgressBar) {
            _progressbar.hidden = NO;
        } else {
            [_indicator startAnimating];
        }
        self.image = self.placeholder == nil ? nil : self.placeholder;
        NSURL *URL = [NSURL URLWithString:_url];
        NSURLRequest *req = [NSURLRequest requestWithURL:URL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.f];
        self.conn = [NSURLConnection connectionWithRequest:req delegate:self];
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    }
}

- (void)cancelLoading{
    [self.conn cancel];
    [_indicator stopAnimating];
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}

- (void)setUrl:(NSString *)url{
    if (_url != url) {
        [_url release];
        _url = [url copy];
        if (self.autoLoading) {
            [self startLoading];
        }
    }
}

- (void)setTouchable:(BOOL)touchable{
    _touchable = touchable;
    self.userInteractionEnabled = _touchable;
}

#pragma mark - Touch

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    if (self.touchable) {
        if (_delegate && [_delegate respondsToSelector:@selector(imageViewDidTouch:)]) {
            [_delegate imageViewDidTouch:self];
        }
    }
}

#pragma mark - URLConnection Delegate

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
#ifdef DEBUG
    NSLog(@"%@",error.description);
#endif
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    self.loading = YES;
    
    NSMutableData *data = [[NSMutableData alloc] init ];
    self.recvData = data;
    [data release];
    self.totalLen = response.expectedContentLength;

}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [self.recvData appendData:data];
    if (self.style == kMSImageViewStyleProgressBar) {        
        self.recvLen += data.length;
        _progressbar.progress = self.recvLen*1.f/self.totalLen;
    }
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    if (self.style == kMSImageViewStyleProgressBar) {
        _progressbar.hidden = YES;
        _progressbar.progress = 0.f;
    } else {
        [_indicator stopAnimating];
    }
    NSString *fileName = [self cacheName];
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    [self.recvData writeToFile:[path stringByAppendingPathComponent:fileName] atomically:YES];
    UIImage *image = [UIImage imageWithData:self.recvData];
    
    if (self.useThumbnail) {
        fileName = [[self class] thumbnailCacheNameForUrl:self.url];
        image = [image resizeToSize:
                              CGSizeMake(self.bounds.size.width*2, self.bounds.size.height*2)];
        NSData *data = UIImageJPEGRepresentation(image, .8f);
        [data writeToFile:[path stringByAppendingPathComponent:fileName] atomically:YES];
    } 
    self.image = image;
    self.conn = nil;
    self.recvData = nil;
    if (_completionBlock != NULL) {
        _completionBlock(self);
    }
    if (_delegate && [_delegate respondsToSelector:@selector(imageDidFinishLoading:)]) {
        [_delegate imageDidFinishLoading:self];
    }
    if (self.animatedShow) {
        [self finishingAnimation];
    }
    
    self.loading = NO;
}
@end
